#!/usr/bin/python
import pygame
from  MapConst import *
import Map
import time
import pickle


class logger:

	def info(self,txt):
		print "[INFO] %s" % (txt)

	def error(self,txt):
		print "[ERROR] %s" % (txt)



class LevelEditor:

	def __init__(self):
		self.m_windowSize = (1024,768)

		self.m_guiHeight = 150
		self.m_guiWidth = self.m_windowSize[1]
		self.m_guiSize = (1024,self.m_guiHeight)
		self.m_guiLocation =  (0,1024-400)
		self.m_guiRect = pygame.Rect(self.m_guiSize,self.m_guiLocation)
		self.m_mapSurface = None
		self.m_uiSurface = None
		self.m_spriteFiles = {}
		self.m_smallTileSize = 15 
		self.m_TileSize = 30
		self.m_filledTiles = {} 
		self.m_mapXMax = None
		self.m_mapYMax = None
		self.m_map = Map.Map()
		self.m_selectedTile = None
		self.m_selectedTileName = None

	def setLogger(self,logger):
		self.logger = logger

		

	def initialize(self):
		self.setupMapSurface()
		self.setupUISurface()

		#Lets load our map tile file
		img = pygame.image.load("../../images/temp/walls.png")
		self.m_spriteFiles["wallTiles.png"] =  img
		self.loadTiles()



	def loadTiles(self):
		for tile in tileMap.values():
			print "TILE: ",tile
			fileName =tile["FILE"]
			tmpRect = pygame.Rect(tile["CORDS"],(50,50))
			tile["SURFACE"].blit(self.m_spriteFiles[fileName],(0,0),tmpRect)
			tile["SURFACE"] = pygame.transform.smoothscale(tile["SURFACE"],(self.m_TileSize, self.m_TileSize))

	
	def setupMapSurface(self):
		self.m_mapSurface = pygame.Surface(self.m_windowSize)
		self.m_mapSurface.fill((0,0,0))



	def setupUISurface(self):
		self.m_uiSurface = pygame.Surface(self.m_guiSize)
		self.m_uiSurface.fill((255,255,255))


	def handleUIClick(self,pos):
		for tile in tileMap.values():
			if(tile["LOCATION"].collidepoint(pos)):
				self.m_selectedTile = tile
				

		

	def handleMapClick(self,pos):
		
		if(self.m_selectedTile == None):
			return

		
		#Lets find our tile
		x = pos[0] - (pos[0] %  self.m_smallTileSize)
		y = pos[1] - (pos[1] %  self.m_smallTileSize)
		self.m_filledTiles[(x,y)] = self.m_selectedTile
		self.m_map.addTile((x,y),self.getTileCharacter(self.m_selectedTile))

		if(x > self.m_mapXMax):
			self.m_mapXMax = x
			self.m_map.setMaxX(x)
		
		if(y > self.m_mapYMax):
			self.m_mapYMax = y
			self.m_map.setMaxY(y)
			
		
		return


	def handleClick(self,pos):
		if(self.isOverUI(pos)):
			self.handleUIClick(pos)

		else:
			self.handleMapClick(pos)

	def isOverUI(self,pos):
		print self.m_guiLocation[1]
		if(pos[1] > self.m_guiLocation[1]):
			return True
		return False	

	def getTileCharacter(self,tile):
			for char in tileMap.keys():
				if((tileMap[char]["CORDS"] == tile["CORDS"]) and (tileMap[char]["FILE"] == tile["FILE"])):
					return char
			return None	
				

	def drawMap(self,surface):
		#Lets draw out grid
		
		maxTileX = self.m_mapSurface.get_size()[0] / self.m_smallTileSize
		maxTileY = self.m_mapSurface.get_size()[1] / self.m_smallTileSize
		i=0

		#Draw our X
		for i in range(0,self.m_mapSurface.get_size()[0],self.m_smallTileSize):
			pygame.draw.line(self.m_mapSurface,(255,255,255),(i,1),(i,self.m_mapSurface.get_width()))

		#Draw our Y
		for i in range(0,self.m_mapSurface.get_size()[1],self.m_smallTileSize):
			pygame.draw.line(self.m_mapSurface,(255,255,255),(1,i),(self.m_mapSurface.get_width(),i))


		#Draw our filled tiles 
		for pos in self.m_filledTiles.keys():
			tile = self.m_filledTiles[pos]
			smallSurface = pygame.Surface((self.m_smallTileSize,self.m_smallTileSize))
			smallSurface = pygame.transform.smoothscale(tile["SURFACE"],(self.m_smallTileSize, self.m_smallTileSize))
			self.m_mapSurface.blit(smallSurface,pos)


		#Draw our editor surface
		surface.blit(self.m_mapSurface,(0,0))

	def drawUI(self,surface):
		#Lets draw our tiles as buttons
		offset = 1

		for tile in tileMap.values():
			self.m_uiSurface.blit(tile["SURFACE"],(offset,10))
			tile["LOCATION"] = pygame.Rect((self.m_guiLocation[0] + offset , self.m_guiLocation[1] + 10),(50,50))
			offset += 50 

		#Draw our buttons

		surface.blit(self.m_uiSurface,self.m_guiLocation)


	def saveMap(self):
				


		fd = open("Map.goat-%d" % (time.time()),"w")
		mapObj = pickle.dumps(self.m_map)
		fd.write(mapObj)
		fd.close()
		
		return
		
		
	def draw(self,surface):

		#Our render order
		self.drawMap(surface)	

		self.drawUI(surface)
	



if __name__ == "__main__":


	log = logger()	
	log.info("Loading")


	lvlEditor = LevelEditor()
	lvlEditor.setLogger(log)
	lvlEditor.initialize()

	pygame.init()
	screen = pygame.display.set_mode((1024,768),0,32)

	lvlEditor.draw(pygame.display.get_surface())
	pygame.display.update()
	clock = pygame.time.Clock()



	while(True):
		try:
			clock.tick(40)

			event = pygame.event.poll()
			if event.type == pygame.QUIT:
			 	running = 0
		 	elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
				print "You pressed the left mouse button at (%d, %d)" % event.pos
				print lvlEditor.handleClick(event.pos)
			elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:
				print "You released the left mouse button at (%d, %d)" % event.pos

			elif event.type == pygame.KEYDOWN and event.key == pygame.K_s:
				lvlEditor.saveMap()
				
			lvlEditor.draw(pygame.display.get_surface())
			pygame.display.flip()

		except KeyboardInterrupt:
			print "Done.."
			break



